package com.hamster.crmpre.service.impl;

import com.hamster.crmpre.exception.ExceptionEnum;
import com.hamster.crmpre.exception.LyException;
import com.hamster.crmpre.service.UploadService;
import com.hamster.crmpre.util.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件上传的Service
 * @author Tarry
 * @create 2020/2/13 10:30
 */
@Service
public class UploadServiceImpl implements UploadService {

    //1定义要上传文件 的存放路径
    @Value("${web.upload-path}")
    private String path;
    @Value("${web.domain}")
    private String domain;
    @Value("#{'${web.image}'.split(',')}")
    private List<String> images;
    @Value("#{'${web.video}'.split(',')}")
    private List<String> videos;

    @Override
    public String uploadFile( MultipartFile file){
        //1获得文件名字
        String fileName=file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(fileName,".").toLowerCase();

        //判断文件格式
        if (!images.contains(suffix) && !videos.contains(suffix)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_FORMAT);
        }
        String newFileName = FileUtils.upload(file, path, fileName);
        if(newFileName != null){
            //这里将文件的网址返回
            String fileUrl = domain + "/" + newFileName;
            //System.out.println("文件网址："+fileUrl);
            return fileUrl;
        }
        throw new LyException(ExceptionEnum.INVALID_FILE_FORMAT);
    }
}
